import hashlib
from model import BaseModel
from sqlalchemy import Column, Integer, String, ForeignKey, Boolean
from sqlalchemy.orm import relationship
from tornado.options import options


class User(BaseModel):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    password = Column(String(500))
    username = Column(String(200))
    is_superuser = Column(Boolean(False))
    host_id = Column(Integer, ForeignKey('host_computer.id'))
    hosts = relationship("HostComputer", backref='users')

    def __repr__(self):
        return "<HostComputer(id='%d',name='%s',passwd='%s'')>" % (
            self.id, self.name, self.password,)

    def encrypt_password(self):
        salt = self.get_salt()
        self.password = hashlib.sha512(self.password + salt).hexdigest()

    def get_salt(self):
        salt = options.salt or 'e176369e929743b3bfd675f29e44125d'
        return salt

    def check_password_is_correct(self, password):
        salt = self.get_salt()
        return hashlib.sha512(password + salt).hexdigest() == self.password


class Group(BaseModel):
    __tablename__ = 'group'

    id = Column(Integer, primary_key=True)
    name = Column(String(200))
    host_id = Column(Integer, ForeignKey('host_computer.id'))
    user_id = Column(Integer, ForeignKey('user.id'))
    hosts = relationship("HostComputer", backref='groups')
    users = relationship("User", backref='groups')

    def __repr__(self):
        return "<HostComputer(id='%d',name='%s'')>" % (
            self.id, self.name,)
